package Evaluation;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

public class MeanAveragePrecision {
	private BufferedReader br;
	private HashMap<String, HashSet<String>> targets;
	private String currentMWE;
	private ArrayList<Integer> positions;

	public MeanAveragePrecision() throws FileNotFoundException {
		br = new BufferedReader(new FileReader(new File("out/correct")));
		targets = new HashMap<String, HashSet<String>>();
		positions = new ArrayList<Integer>();
		
	}

	public void constuctTargetMap() throws IOException {
		String line = "";
		String[] split;
		HashSet<String> set;
		while ((line = br.readLine()) != null) {
			split = line.split(" ");
			if (targets.containsKey(split[0])) {
				set = targets.get(split[0].trim());
			} else {
				set = new HashSet<String>();
			}
			set.add(split[1].trim());
			targets.put(split[0].trim(), set);
		}
		printTarget();
		computeMAP();
	}

	public void computeMAP() throws IOException {
		File dir = new File("results/results_200_sorted");
		File[] files = dir.listFiles();
		BufferedReader brRes;

		for (File file : files) {
			brRes = new BufferedReader(new FileReader(file));
			currentMWE = file.getName().split("__")[0].replaceFirst("200_", "")
					.replaceFirst("20_", "").replaceFirst("6_", "")
					.replaceFirst("results_", "").trim();
			if(targets.containsKey(currentMWE)){
				processOneMWE(brRes);
			}
		}
		computeAverage();
	}

	public void printTarget() {
		for (String s : targets.keySet()) {
			System.out.println(s + " " + targets.get(s).toString());
		}
	}

	public void processOneMWE(BufferedReader brRes) throws IOException {
		String line = "";
		String[] split;
		String currentResult ="";
		int counter =0;
		HashSet<String> resultSet = targets.get(currentMWE);
		while ((line = brRes.readLine()) != null) {
			counter++;
			currentResult = line.split(" ")[1];
			if(resultSet.contains(currentResult))
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			{
				positions.add(counter);
				System.out.println("!!! "+currentMWE+" "+counter+" "+currentResult);
				break;
			}
//			if(counter>15){
//				System.out.println("<<< "+currentMWE+" "+counter+" "+currentResult);
//
//				positions.add(0);
//				break;
//			}
			
		}
	}
	
	public void computeAverage(){
		double precicions =0.0;
		for(int i: positions){
			if(i>0){
			precicions+= 1.0/(double) i;

			}

			
		}
		precicions = precicions/(double) positions.size();
		System.out.println("MAP "+ precicions);
	}
	
}
